<?php

class multitender_action_billing extends multitender_action {

    private $error = 'Сработала система безопасности сервиса. Попробуйте начать <a href="/tenders/billing/">сначала</a>.';
    function  __construct() {
        parent::__construct();
        $this->db      = & $this->conf['dbs']['person'];
    }

    function show($user_id) {
        $this->conf['page_title'] = 'Выставить счёт';

        $step = (isset($_GET['step'])) ? (int)$_GET['step'] : 1;
        if (!in_array($step, array(1, 2, 3))) {
            $step = 1;
        }
        $tpl=$this->new_tpl();
        $bl = new multitender_model_billing();
        $rates = $bl->get_rates();
        switch ($step) {
            case 3:
                // Вид платежа
                if ($_GET['type_payment'] == 'electron') {
                    $tpl->assign('kind_rate', 'Электронный платёж');
                    $tpl->assign('type_payment', 'electron');
                } elseif ($_GET['type_payment'] == 'cashless') {
                    $firm = new multitender_model_firm();
                    $firm = $firm->load($user_id);
                    if (!$firm) {
                        die($this->error);
                    }
                    $tpl->assign('kind_rate', 'Безналичный расчёт');
                    $tpl->assign('type_payment', 'cashless');
                } else {
                    die ($this->error);
                }
                // Тариф
                if ($_GET['kind_rates_id'] == 2) { // розница
                    if ((int)$_GET['count'] < 1) {
                        die($this->error);
                    }
                    $tpl->assign('tariff', 'Розничный');
                    $tpl->assign('kind_rates_id', 2);
                    $tpl->assign('count', (int)$_GET['count'] .  ' ' . factor('тендер', (int)$_GET['count']));
                    $tpl->assign('rate', 6);
                    $tpl->assign('count_tender', (int)$_GET['count']);
                    $tpl->assign('summ', $rates[5]['summa'] * (int)$_GET['count'] . ' рублей');
                } elseif ($_GET['kind_rates_id'] == 1) { // безлимит
                    $tpl->assign('tariff', 'Безлимитный');
                    if (!in_array($_GET['rate'], array(1,2,3,4,5))) {
                        die($this->error);
                    }
                    foreach ($rates as $rate) {
                        if ($rate['id'] == (int)$_GET['rate']) {
                            $tpl->assign('count', $rate['name']);
                            $tpl->assign('rate', $rate['id']);
                            $tpl->assign('summ', $rate['summa'] . ' рублей');
                        }
                    }
                    $tpl->assign('kind_rates_id', 1);
                } else {
                    die($this->error);
                }
                 return $tpl->fetch('bill3.tpl');
                break;
            case 2:
                if ($_GET['type_payment'] == 'electron') {
                    $tpl->assign('type_payment', 'electron');
                } elseif ($_GET['type_payment'] == 'cashless') {
                    $tpl->assign('type_payment', 'cashless');
                } else {
                    die ($this->error);
                }
                $tpl->assign('rates',  $rates);
                return $tpl->fetch('bill2.tpl');
                break;
            case 1:
            default:
                if (isset($_GET['el']))
                    $tpl->assign('el', 1);
                $firm = new multitender_model_firm();
                $firm = $firm->load($user_id);
                if (!$firm) {
                    $tpl->assign('first',  true);
                } else {
                    $tpl->assign('first',  false);
                    $tpl->assign('name',   $firm['name']);
                }
                return $tpl->fetch('bill1.tpl');
        }

        //return $tpl->fetch('bill1.tpl');

        //$bl = new multitender_model_billing();

        //$tpl->assign('action', $this->conf['pref']['link_base'].'action=billing&task=exhibit');

        //return $tpl->fetch('billing.tpl');
    }

    function exhibit($user_id) {
        $this->conf['page_title'] = 'Мои платежи';

        // Выставить счёт
        $bill=array();

        $bl = new multitender_model_billing();

        $rates = $bl->get_rates();
        $kind_rates = $bl->get_kind_rates();
        $tpl=$this->new_tpl();
        $id_now = 0;

        if (isset($_GET['print']) && is_numeric($_GET['print'])) {
            //$tpl->assign('print', '<script type="text/javascript">setTimeout(location.href="/ajax.php?action=billing&task=payment_view&payment_id=' . (int)$_GET['print'] . '",5000);"</script>');
            echo '<meta http-equiv="refresh" content="3; url=/ajax.php?action=billing&task=payment_view&payment_id=' . (int)$_GET['print'] . '">';
        }
        if (!empty($_POST)) {
            $bl->setAccess_ins($user_id);

            if (!in_array($_POST['type_payment'], array('electron', 'cashless'))) {
                die($this->error);
            } else {
                $type_payment  = $_POST['type_payment'];
                $print = ($type_payment == 'cashless') ? 1 : 0;
            }

            $kind_rates_id =  isset($_POST['kind_rates_id']) ? (int)$_POST['kind_rates_id'] : NULL;

            if (is_numeric($kind_rates_id)) {
                switch ($kind_rates_id) {
                    case 1: // Без лимитные
                        $rates_id = & $_POST['rate'] ? $_POST['rate'] : 0;
                        foreach ($rates as $r) {
                            if ($r['id']==$rates_id && $r['kind_rates_id']==$kind_rates_id) {
                                $count = $r['count'];
                                $summa = $r['summa'];
                            }
                        }
                        $id_now = $bl->add_payment($user_id, $kind_rates_id, $rates_id, $count, $summa, $type_payment);
                        // FIXME загрузка kind_rates из базы данных
                        $this->send_notice($user_id, $count, $summa, 'Безлимитный');
                        break;
                    case 2: // Лимитные
                        $count = &$_POST['count_tender'] ? $_POST['count_tender'] : 0;
                        if ($count) {
                            $rates_id = 6;
                            foreach ($rates as $r) {
                                if ($r['kind_rates_id']==2) {
                                    $x = $r['summa'];
                                }
                            }

                            $summa = $x * $count;
                            $id_now = $bl->add_payment($user_id, $kind_rates_id, $rates_id, $count, $summa, $type_payment);
                            $this->send_notice($user_id, $count, $summa, 'Розничный');
                        } else {
                            die($this->error);
                        }
                        break;
                }
            } else {
                die($this->error);
            }

            if (!empty($_POST['paid'])) {
                foreach ($_POST['paid'] as $k => $v) {
                    $payable[$v][] = $k;
                }
                $bl->set_status_payments($user_id, $payable);
            }
        
            if ($print) {
                header('Location: ' . $_SERVER['REQUEST_URI'] . "&print=$id_now");
            } else {
                header('Location: ' . $_SERVER['REQUEST_URI']);
            }

        }

        $pays = $bl->get_payments_no($user_id, 0, $this->conf['db_conf']['person']['billing_exhibit_count']);
        

        if ($pays) {
            foreach ($pays as &$pay) {
                foreach ($kind_rates as $kr) {
                    if ($pay['kind_rates_id']==$kr['id']) {
                        $pay['kind_rates'] = $kr['name'];
                    }
                }
                if ($pay['type_payment']=="electron") {
                    $rb = $this->new_action("robokassa");
                    $pay['robokasse'] = $rb->button($pay['summa'], $pay['id'], "Оплата услуг " . $this->conf['pref']['site_name']);
                    $pay['type_payment_rus'] = "Электронный";
                } else {
                    $pay['type_payment_rus'] = "Безналичный";
                }
                $pay['datetime']=date2str($pay['datetime']);
                $pay['datetime_adopted']=date2str($pay['datetime_adopted']);

                if ( $pay['id'] == $id_now ) {
                    $pay['NOW'] = true;
                }
            }
            $tpl->assign('pays', $pays);
        }



        $rectopg = 10;
        $page = @ $_GET['page'] ? $_GET['page'] : 1;
        $offset = $rectopg*($page-1);
        $paid = $bl->get_payments_yes($user_id, $offset, $rectopg);//скроллер!!!
        $total = $paid['total'];
        unset($paid['total']);
        $scrol = $this->new_action("scrol");
        $scrol->link = '/tenders/billing/?task=exhibit' .$scrol->link;
        $scrol->total = $total;
        $scrol->onpage = $rectopg;
        $tpl->assign('scrol', $scrol->run());


        
        if ($paid) {
            foreach ($paid as &$pay) {
                foreach ($kind_rates as $kr) {
                    if ($pay['kind_rates_id']==$kr['id']) {
                        $pay['kind_rates'] = $kr['name'];
                    }
                }
                if ($pay['type_payment']=="electron") {
                    $rb = $this->new_action("robokassa");
                    $pay['robokasse'] = $rb->button($pay['summa'], $pay['id'], "Оплата услуг " . $this->conf['pref']['site_name']);
                    $pay['type_payment_rus'] = "Электронный";
                } else {
                    $pay['type_payment_rus'] = "Безналичный";
                }
                $pay['datetime']=date2str($pay['datetime']);
                $pay['datetime_adopted']=date2str($pay['datetime_adopted']);

                if ( $pay['id'] == $id_now ) {
                    $pay['NOW'] = true;
                }
            }
            $tpl->assign('paid', $paid);
        }

        $tpl->assign('email', $this->conf['tender']['subscribe']['email']);


        return $tpl->fetch('payments.tpl');
    }

    /**
     * Проверка и очистка данных с формы "реквизиты организации"
     * передача по ссылке
     * @param  array $arr
     * @return boolen
     */
    private function validate_details_firm(&$arr) {
        $firm_obj = new multitender_model_firm();
        return $firm_obj->validate_firm($arr);
    }

    function details_firm($user_id) {

        $arr = !empty($_POST) ? $_POST : null;
        $err=true;

        if (!empty($arr) && isset($arr['submit'])) {
            if ($this->validate_details_firm($arr)) {
                $arr['user_id']=$user_id;
                $ff = new multitender_model_firm();
                $ff->save($arr);
                header("Location:".$this->conf['pref']['link_base_http']."tenders/cabinet");
                exit();
            }
        }
        $ff = new multitender_model_firm();

        if (empty($arr)) {
            $arr=$ff->load($user_id);
        }

        $tpl=$this->new_tpl();
        $action = $this->conf['pref']['link_base']."action=billing&task=details_firm";
        $tpl->assign("action", $action);
        $tpl->assign('arr', $arr);
        return $tpl->fetch("form_firm.tpl");
        
    }

    function payment_set($user_id) {
        $payment_id = & $_GET['payment_id'] ? $_GET['payment_id'] : 0;
        if ($payment_id) {
            $bl = new multitender_model_billing();
            $bl->paid($payment_id);
        }
    }

    function payment_view($user_id) {
        $payment_id = (int) @ $_GET['payment_id'];
        if ($payment_id) {
            $bl = new multitender_model_billing();
            $payment=$bl->get_payment($payment_id);
            if (!$payment) {
                exit('no this payment');
            }
            if (($payment['user_id'] != $user_id) && ($this->conf['user']['right'] < 50)) {
                exit("It's not own to you!");
            }

            $firm_obj = new multitender_model_firm();
            $firm_info = $firm_obj->load_prepared($payment['user_id']);

            if ( ! $firm_info['address_full'] ) {
                $firm_info['address_full'] = $firm_info['domicile_full'];
            }

            $rates_name = $bl->get_rate($payment['rates_id']);
            $bull=array(
                    '##ID##'         => $payment['id'],
                    '##INN##'        => $firm_info['INN'],
                    '##KPP##'        => $firm_info['KPP'],
                    '##DOMICILE##'   => $firm_info['domicile_full'],
                    '##ADDRESS##'    => $firm_info['address_full'],
                    '##PAYER##'      => $firm_info['contact'],
                    '##TOTAL##'      => $payment['summa'].".00",
                    '##DATE##'       => date2rus($payment['datetime'])." г.",
                    '##TOTAL_STR##'  => num2str($payment['summa']),
                    '##NAME##'       => $firm_info['name'],
                    '##TARIF_NAME##' => $rates_name['name']
            );
            generate_rtf_make($this->conf['dir']['templ'].'/templates/tpl_bull.rtf', $bull, $payment_id);
        }
    }

    function buy_tender($user_id) {
        $item_id = isset($_GET['item_id']) ? $_GET['item_id'] : null;
        $bl = new multitender_model_billing();
        $bl->buy_usertender($user_id, $item_id, 2);
    }

    function buy_delete($user_id) {
        $id = isset($_GET['id']) ? $_GET['id'] : null;
        $bl = new multitender_model_billing();
        if ($bl->set_status_payment($user_id, $id, -1)) {
            return "OK";
        } else {
            return "CANCEL";
        }

    }

    function send_notice($user_id, $count, $summa, $tarif) {
        $user_id      = (int) $user_id;
        $joomla_users = 'ten_users';

        if (empty($this->db_joomla)) {
            $this->db_joomla = ADONewConnection($this->conf['db_conf']['joomla']['dsn']);
            $this->db_joomla->Execute('set names utf8');
        }

        $joomla_id = $this->db->GetOne("SELECT joomla_id FROM users WHERE id=$user_id");
        $user_info = $this->db_joomla->GetRow("SELECT username,email FROM $joomla_users WHERE id=$joomla_id");
        if (empty($user_info)) {
            return false;
        }

        require_once $this->conf['libdir'] . "/util_str2.php";
        require_once $this->conf['libdir'] . '/phpmailer/class.phpmailer.php';

        // TEST
        // $user_info['email'] = 'airrussian@mail.ru';

        $tpl = $this->new_tpl();
        $tpl->assign('email',  $user_info['email']);
        $tpl->assign('login',  $user_info['username']);
        $tpl->assign('tarif',  $tarif);
        $tpl->assign('summa',  $summa);
        $tpl->assign('count',  $count);
        $content = $tpl->fetch('billing_notice.tpl');

        $mail = new PHPMailer(true);
        try {
            $mail->IsSendmail();
            $mail->CharSet = 'UTF-8';
            $mail->SetFrom($this->conf['tender']['subscribe']['email'], $this->conf['tender']['subscribe']['name']);
            $mail->AddAddress($user_info['email'], $user_info['username']);
            $mail->Subject = $this->conf['pref']['site_name'] . ' :: оповещение о выставлении счёта';
            $mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
            $mail->MsgHTML($content);
            $mail->Send();
            return true;
        } catch (phpmailerException $e) {
            echo $user_info['email'];
            echo $e->errorMessage(); //Pretty error messages from PHPMailer
        } catch (Exception $e) {
            echo $user_info['email'];
            echo $e->getMessage(); //Boring error messages from anything else!
        }
        return false;
    }

    function run() {
        // Много задач
        $user_id = $GLOBALS['tenders']['conf']['user']['id'];
        if (!$user_id) {
            $tpl = $this->new_tpl();
            return $tpl->fetch("msg_auth.tpl");
        }

        $task = & $_GET['task'] ? $_GET['task'] : 'show';

        switch ($task) {
            case 'exhibit'      : return $this->exhibit($user_id);
                break;  // Добавление нового счёта
            case 'details_firm' : return $this->details_firm($user_id);
                break;  // Форма редактирования фирмы
            case 'payment_set'  : return $this->payment_set($user_id);
                break;  //
            case 'payment_view' : return $this->payment_view($user_id);
                break;
            case 'buy_delete'   : return $this->buy_delete($user_id);
                break;
            case 'buy_tender'   : return $this->buy_tender($user_id);
                break;  // Задача на открытия доступа пользователя к тендеру
            default             : return $this->show($user_id);
                break;  // По умолчанию страница "выставить счёт"
        }
    }

}
